<?php
session_start();

include ('lib/config.php');
include ('lib/oauth_lib.php');
include ('lib/twitteroauth.php');
include ('lib/twitter.php');

if (isset($_REQUEST['oauth_token'])) {
	if($_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
		$_SESSION['oauth_status'] = 'oldtoken';
		session_destroy();
		@ unlink(TW_OAUTH);
		die('OAuth失败,<a href="index.php">返回首页</a>');
	}
	else{
		$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

		$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);

		$_SESSION['access_token'] = $access_token;
		
		unset($_SESSION['oauth_token']);
		unset($_SESSION['oauth_token_secret']);
				
		$content = $access_token['oauth_token']."\n".$access_token['oauth_token_secret'];
		file_put_contents(TW_OAUTH,$content);
		
		if (200 == $connection->http_code) {
			$_SESSION['login_status'] = 'verified';
			$t = getTwitter();
			$user = $t->veverify();

			echo ('OAuth成功,<a href="index.php">返回首页</a>');
		} else {
			session_destroy();
			unlink(TW_OAUTH);
			echo ('OAuth失败,<a href="index.php">返回首页</a>');
		}
	}

}else{
	$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
	
	$scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
	$port = $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443 ? ':'.$_SERVER['SERVER_PORT'] : '';
	$oauth_callback = $scheme . '://' . $_SERVER['HTTP_HOST'] . $port . $_SERVER['REQUEST_URI'];
	
	$request_token = $connection->getRequestToken($oauth_callback);
	

	$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
	$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

	
	switch ($connection->http_code) {
	case 200:
		/*NEW*/
		$url = $connection->getAuthorizeURL($request_token['oauth_token']);
		/*NEW*/
		header('Location: ' . $url); 
		break;
	default:
		echo '无法连接到 Twitter.请刷新页面或重试.';
		break;
	}
}
?>